package com.open.rbac.controller.sys;

import java.util.List;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.open.center.common.model.CommonResult;
import com.open.rbac.model.dto.sys.UserDto;
import com.open.rbac.model.query.UserQuery;
import com.open.rbac.model.vo.sys.UserVo;
import com.open.rbac.model.vo.sys.group.UpdatePassword;
import com.open.rbac.model.vo.sys.group.UserCreate;
import com.open.rbac.model.vo.sys.group.UserUpdate;
import com.open.rbac.service.sys.IUserService;

/**
 * 用户控制器
 *
 * @author Riche's
 * @since 2022/8/12
 */
@Slf4j
@Tag(name = "用户管理", description = "用户控制器")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "成功",
        content = {@Content(schema = @Schema(implementation = UserDto.class))}),
})
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/v1/sys/user")
public class UserController {

    private final IUserService userService;

    @Operation(summary = "新增用户")
    @Validated(UserCreate.class)
    @PostMapping()
    public CommonResult<UserDto> create(@Valid @RequestBody UserVo userVo) {
        return CommonResult.success(userService.create(userVo));
    }

    @Operation(summary = "更新用户")
    @Validated(UserUpdate.class)
    @PutMapping()
    public CommonResult<UserDto> update(@Valid @RequestBody UserVo userVo) {
        return CommonResult.success(userService.update(userVo));
    }

    @Operation(summary = "重置密码")
    @PutMapping("/reset/password/{id}")
    public CommonResult<Void> resetPassword(@PathVariable String id) {
        userService.resetPassword(id);
        return CommonResult.success();
    }

    @Operation(summary = "更新用户密码")
    @Validated(UpdatePassword.class)
    @PutMapping("/update/password")
    public CommonResult<Void> updatePassword(@Valid @RequestBody UserVo userVo) {
        userService.updatePassword(userVo.getId(), userVo.getPassword());
        return CommonResult.success();
    }

    @Operation(summary = "更新用户头像")
    @PutMapping("/update/avatar")
    public CommonResult<Void> updateAvatar(@RequestBody UserVo userVo) {
        userService.updateAvatar(userVo.getId(), userVo.getAvatar());
        return CommonResult.success();
    }

    @Operation(summary = "用户信息")
    @GetMapping("/{id}")
    public CommonResult<UserDto> get(@PathVariable String id) {
        return CommonResult.success(userService.findById(id));
    }

    @Operation(summary = "批量启用|禁用用户")
    @PutMapping("/enable")
    public CommonResult<Void> enable(
        @RequestParam boolean enable,
        @RequestBody
        @NotEmpty(message = "用户ID列表为必选项")
        List<String> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            if (enable) {
                userService.enable(ids);
            } else {
                userService.disable(ids);
            }
        }
        return CommonResult.success();
    }

    @Operation(summary = "更新用户与角色关系")
    @PutMapping("/role/{userId}")
    public CommonResult<Void> updateRoles(@PathVariable String userId,
                                          @NotEmpty(message = "角色列表为必选项")
                                          @RequestBody List<String> roleIds) {
        userService.createRoles(userId, roleIds);
        return CommonResult.success();
    }

    @Operation(summary = "更新用户与组织机构关系")
    @PutMapping("/organization/{userId}")
    public CommonResult<Void> updateOrganizations(@PathVariable String userId,
                                                  @NotEmpty(message = "组织机构列表为必选项")
                                                  @RequestBody List<String> organizationIds) {
        userService.createOrganizations(userId, organizationIds);
        return CommonResult.success();
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    public CommonResult<Void> deleteById(@PathVariable String id) {
        userService.deleteById(id);
        return CommonResult.success();
    }


    @Operation(summary = "按用户名查询用户")
    @GetMapping("/by_username")
    public CommonResult<UserDto> getByUsername(@RequestParam(required = false) String id,
                                               @RequestParam String username) {
        UserDto userDto = userService.findByUsername(username);
        if (userDto != null && userDto.getId().equals(id)) {
            return CommonResult.success(null);
        }
        return CommonResult.success(userDto);
    }

    @Operation(summary = "查询有效的用户列表")
    @GetMapping("/list")
    public CommonResult<List<UserDto>> list() {
        return CommonResult.success(userService.list());
    }

    @Operation(summary = "用户分页")
    @PostMapping("/page")
    public CommonResult<Page<UserDto>> page(@Valid @RequestBody UserQuery query) {
        return CommonResult.success(userService.page(query));
    }

}
